package cn.xz.zgsg.util

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.TextUtils
import android.util.TypedValue
import androidx.core.content.ContextCompat
import cn.xz.zgsg.base.BaseApplication

object AppHelper {

    private var VERSIONNAME: String? = null

    //获取当前版本号
    fun getAppVersionName(): String? {
        if (VERSIONNAME != null && VERSIONNAME != "") {
            return VERSIONNAME!!
        }
        try {
            val packageManager = BaseApplication.getContext().packageManager
            val packageInfo =
                packageManager.getPackageInfo(BaseApplication.getContext().packageName, 0)
            VERSIONNAME = packageInfo.versionName
            if (TextUtils.isEmpty(VERSIONNAME)) {
                return ""
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return VERSIONNAME
    }

    //获取当前Code号
    private var VERSIONCODE: String? = null

    @SuppressLint("NewApi")
    fun getAppVersionCode(): String? {
        //   var versionCode = "0"
        if (VERSIONCODE != null && VERSIONCODE != "") {
            return VERSIONCODE!!
        }
        try {
            val packageManager = BaseApplication.getContext().packageManager
            val packageInfo = packageManager.getPackageInfo(BaseApplication.getContext().packageName, 0)
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                VERSIONCODE = packageInfo.longVersionCode.toString()
            } else {
                VERSIONCODE = packageInfo.versionCode.toString()
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return VERSIONCODE
    }


    /**
     * dp转px
     *
     * @param dpVal
     * @return
     */
    fun dp2px(dpVal: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpVal.toFloat(),
            BaseApplication.getContext().resources.displayMetrics
        ).toInt()
    }

    /**
     * dp转px
     *
     * @param dpVal
     * @return
     */
    @JvmStatic
    fun dp2px(dpVal: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpVal,
            BaseApplication.getContext().resources.displayMetrics
        ).toInt()
    }

    fun getDrawable(id: Int): Drawable?{
        return ContextCompat.getDrawable(BaseApplication.getContext(),id)
    }
}